import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class RefreshPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _RefreshPage();
  }
}

class _RefreshPage extends State<RefreshPage> {
  ScrollController _scrollController = new ScrollController();
  List<int> items = List.generate(20, (i) => i);
  bool isLoading = false;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        print("loadMore");
        _getMoreData();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Refresh"),
        centerTitle: true,
      ),
      body: RefreshIndicator(
        child: ListView.builder(
            controller: _scrollController,
            itemCount: items.length + 1,
            itemBuilder: (context, index) {
              if (index == items.length) {
                return _buildLoadText();
              } else {
                return ListTile(
                  title: Text("item$index"),
                );
              }
            }),
        onRefresh: _refresh,
      ),
    );
  }

  Widget _buildLoadText() {
    return Container(
      child: Padding(
        padding: const EdgeInsets.all(18.0),
        child: Opacity(
          opacity:1,
          child: Center(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
              Container(
                child: CircularProgressIndicator(),
                width: 25,
                height: 25,
              ),
              Container(
                child: Text("加载中..."),
                margin: EdgeInsets.only(left: 10),
              )
            ],),
          ),
        ),
      ),
      color: Colors.white70,
    );
  }

  Future<Null> _refresh() async {
    await Future.delayed(Duration(seconds: 3), () {
      print('refresh');
      setState(() {
        items.clear();
        items = List.generate(20, (i) => i);
        return null;
      });
    });
  }

  Future _getMoreData() async {
    if (!isLoading) {
      isLoading = true;
      List<int> newEntries =
          await imitateHttpRequest(items.length, items.length + 10);
      setState(() {
        isLoading = false;
        items.addAll(newEntries);
      });
    }
  }

  Future<List<int>> imitateHttpRequest(int from, int to) async {
    return Future.delayed(Duration(seconds: 2), () {
      return List.generate(to - from, (i) => i + from);
    });
  }
  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }
}
